using System;
using System.Collections.Generic;
using System.Text;

namespace ViewStateEliminator.Data
{
    /// <summary>
    /// Provides the ability to save viewstate into session. The session will double as a viewstate server.
    /// </summary>
    public class ViewStateSessionStorage : IViewstateStorage
    {
        private System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<object, string>> StorageList
        {
            get
            {
                if (System.Web.HttpContext.Current.Session["ViewStateSessionStorage"] == null)
                {
                    System.Web.HttpContext.Current.Session["ViewStateSessionStorage"] = new System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<object, string>>();
                }
                return ((System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<object, string>>)System.Web.HttpContext.Current.Session["ViewStateSessionStorage"]);
            }
        }

        #region IViewstateStorage Members
        public void Add(KeyValuePair<object, string> viewstateItem)
        {
            StorageList.Add(viewstateItem);
        }
        public KeyValuePair<object, string> Get(object key)
        {
            System.Collections.Generic.KeyValuePair<object, string> retItem = new KeyValuePair<object, string>();
            foreach (System.Collections.Generic.KeyValuePair<object, string> item in this.StorageList)
            {
                if (item.Key.ToString().ToLower().Equals(key.ToString().ToLower()))
                {
                    retItem = item;
                }
            }
            Remove(retItem.Key);
            return retItem;
        }
        public void Remove(object key)
        {
            System.Collections.Generic.KeyValuePair<object, string> itemToRemove = new System.Collections.Generic.KeyValuePair<object, string>();
            foreach (System.Collections.Generic.KeyValuePair<object, string> item in this.StorageList)
            {
                if (item.Key == key)
                {
                    itemToRemove = item;
                }
            }
            this.StorageList.Remove(itemToRemove);
        }
        #endregion
    }
}
